package com.lyeducation.controllers.course;

import com.lyeducation.controllers.base.BaseController;
import com.lyeducation.controllers.dto.CourseDTO;
import com.lyeducation.core.base.TokenConstants;
import com.lyeducation.core.course.CourseService;
import com.lyeducation.entities.course.CourseEntity;
import com.lyeducation.entities.course.middle.UserCourseScoreEntity;
import com.lyeducation.repository.CourseRepository;
import com.lyeducation.security.config.SecurityPrincipalContext;
import com.lyeducation.util.StringUtils;
import com.lyeducation.util.controllerUtil.JsonConstans;
import com.lyeducation.util.controllerUtil.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;

@Api(
        tags = {"课程course-api"},
        description = "课程模块接口{mId}需要传入菜单id"
)
@RestController
@RequestMapping("course/{mid}")
public class CourseController extends BaseController<CourseEntity> {
    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseRepository courseRepository;

    @Override
    public JsonResult onLoad() {
        if (!SecurityPrincipalContext.checkHasAdminOrGeneralAdminRole()) {
            return JsonResult.putFail();
        }
        return JsonResult.putSuccess(courseService.selCourseByPage(10, 1));
    }

    /**
     * 添加更新课程
     *
     * @param courseDTO
     * @return
     */
    @ApiOperation("添加更新课程")
    @PostMapping("addUpdCourse")
    public JsonResult addUpdCourse(@RequestBody @ApiParam(value = "课程") CourseDTO courseDTO) {
        if (!SecurityPrincipalContext.checkHasAdminOrGeneralAdminRole()) {
            return JsonResult.putFail();
        }
        if (courseService.addUpdCourse(courseDTO) != null) {
            return JsonResult.putSuccess();
        }
        return JsonResult.putFail();
    }

    @GetMapping("/courseInfo/{courseId}")
    public JsonResult courseInfo(@PathVariable String courseId) {
        return JsonResult.putSuccess(courseService.courseInfo(courseId));
    }

    @PostMapping("/updateCourse")
    public JsonResult updateCourse(@RequestBody com.lyeducation.controllers.dto.CourseDTO courseDTO) {
        if (!SecurityPrincipalContext.checkHasAdminOrGeneralAdminRole()) {
            return JsonResult.putFail();
        }
        if (courseService.updateCourse(courseDTO) != null) {
            return JsonResult.putSuccess();
        }
        return JsonResult.putFail();
    }

    @GetMapping("/deleteCourse/{courseId}")
    public JsonResult deleteCourse(@PathVariable String courseId) {
        return JsonResult.putSuccess(courseService.deleteCourse(courseId));
    }

    /**
     * 课程搜索
     */
    @PostMapping("/searchCourse")
    public JsonResult searchCourse(@RequestBody CourseDTO courseDTO) {
        return JsonResult.putSuccess(courseService.searchCourse(courseDTO));
    }

    /**
     * 课程列表
     */
    @GetMapping("/courseList/{pageNo}/{pageSize}")
    public JsonResult courseList(
            @RequestParam("categoryId") String categoryId,
            @PathVariable("pageNo") int pageNo,
            @PathVariable("pageSize") int pageSize) {
        return JsonResult.putSuccess(courseService.courseEntityList(categoryId, pageNo, pageSize));
    }

    /**
     * 热门课程
     */
    @GetMapping("/popularCourse/{pageNo}/{pageSize}")
    public JsonResult popularCourse(
            @PathVariable("pageNo") int pageNo, @PathVariable("pageSize") int pageSize) {
        return JsonResult.putSuccess(courseService.popularCourse(pageNo, pageSize));
    }

    /**
     * 首页课程详情
     */
    @GetMapping("/courseInfoIndex/{courseId}")
    public JsonResult courseInfoIndex(@PathVariable("courseId") String courseId) {
        return JsonResult.putSuccess(courseService.courseInfoIndex(courseId));
    }

    /**
     * 设置是否热推
     */
    @GetMapping("/isPopularCourse")
    public JsonResult isPopularCourse(
            @RequestParam("courseId") String courseId, @RequestParam("popularCode") int popularCode) {
        if (courseService.isPopularCourse(courseId, popularCode)) {
            return JsonResult.putSuccess();
        } else {
            return JsonResult.putFail();
        }
    }

    /**
     * 设置是否轮播
     */
    @GetMapping("/isCarousel")
    public JsonResult isCarousel(
            @RequestParam("courseId") String courseId, @RequestParam("carousel") int carousel) {
        if (courseService.isCarousel(courseId, carousel)) {
            return JsonResult.putSuccess();
        } else {
            return JsonResult.putFail();
        }
    }

    /**
     * 获取轮播图
     */
    @GetMapping("/carousel")
    public JsonResult carousel() {
        return JsonResult.putSuccess(courseService.carousel());
    }

    /**
     * 获取课程类型 0为免费课程，1为会员专享，2为收费课程
     */
    @GetMapping("/videoAccessRole/{videoAccessRole}")
    public JsonResult videoAccessRole(@PathVariable("videoAccessRole") int videoAccessRole) {
        if (StringUtils.isNotBlank(String.valueOf(videoAccessRole))) {
            return JsonResult.putSuccess(courseService.videoAccessRole(videoAccessRole));
        }
        return JsonResult.putFail("参数错误！");
    }

    //    @ApiOperation(value = "查询课程评分", notes = "用户查询自身对课程的评分")
    //    @GetMapping("selCourseScore/{courseId}")
    //    public JsonResult selCourseScore(@PathVariable String courseId) {
    //        LinkedHashMap linkedHashMap = new LinkedHashMap();
    //        linkedHashMap.put("userId", SecurityPrincipalContext.getUserDetailsImpl().getId());
    //        linkedHashMap.put("courseId", courseId);
    //        List<UserCourseScoreEntity> userVideoScoreEntityList =
    // courseRepository.findByFileds(UserCourseScoreEntity.class, linkedHashMap);
    //        if (userVideoScoreEntityList != null && userVideoScoreEntityList.size() == 1) {
    //
    //            return JsonResult.putSuccess(userVideoScoreEntityList.get(0));
    //        }
    //        return JsonResult.putFail("查询该课程评分失败");
    //    }

    @ApiOperation(value = "用户查询自身对课程的评分", notes = "用户查询自身对课程的评分说事实")
    @GetMapping("selUserCourseScore/{courseId}")
    public JsonResult selUserCourseScore(@PathVariable String courseId) {
        LinkedHashMap linkedHashMap = new LinkedHashMap();
        linkedHashMap.put("userId", SecurityPrincipalContext.getUserDetailsImpl().getId());
        linkedHashMap.put("courseId", courseId);
        List<UserCourseScoreEntity> userVideoScoreEntityList =
                courseRepository.findByFileds(UserCourseScoreEntity.class, linkedHashMap);
        if (userVideoScoreEntityList != null && userVideoScoreEntityList.size() == 1) {

            return JsonResult.putSuccess(userVideoScoreEntityList.get(0));
        }
        return JsonResult.putFail("查询该课程评分失败");
    }

    @ApiOperation(value = "用户添加课程评分", notes = "用户添加课程评分")
    @PostMapping("addUserCourseScore")
    public JsonResult addUserCourseScore(@RequestBody UserCourseScoreEntity userVideoScoreEntity) {
        if (StringUtils.trimToNull(userVideoScoreEntity.getCourseId()) != null) {
            CourseEntity videoEntity = courseRepository.findById(userVideoScoreEntity.getCourseId());
            if (videoEntity == null) {
                JsonResult.putFail("未查询到该课程无法添加评分");
            }
            LinkedHashMap linkedHashMap = new LinkedHashMap();
            linkedHashMap.put("userId", SecurityPrincipalContext.getUserDetailsImpl().getId());
            linkedHashMap.put("courseId", userVideoScoreEntity.getCourseId());
            List<UserCourseScoreEntity> userVideoScoreEntityList =
                    courseRepository.findByFileds(UserCourseScoreEntity.class, linkedHashMap);
            if (userVideoScoreEntityList != null && userVideoScoreEntityList.size() == 1) {
                return JsonResult.putFail(
                        SecurityPrincipalContext.getUserDetailsImpl().getUsername() + "已经存在对该视频的评分了,添加失败");
            }
            userVideoScoreEntity.setId(TokenConstants.generateUserId());
            userVideoScoreEntity.setUserId(SecurityPrincipalContext.getUserDetailsImpl().getId());
            courseRepository.save(userVideoScoreEntity);

            videoEntity.setTotalPeopleScoreSize(videoEntity.getTotalPeopleScoreSize() + 1);
            videoEntity.setTotalScore(videoEntity.getTotalScore() + userVideoScoreEntity.getScore());

            return JsonResult.putSuccess();
        }
        //        int score = userVideoScoreEntity.getScore();
        //        VideoEntity videoEntity = videoRepository.findById(userVideoScoreEntity.getVideoId());
        //
        //        List<UserVideoScoreEntity> userVideoScoreEntities =
        //                videoRepository.findByFiled(
        //                        UserVideoScoreEntity.class, "videoId",
        // userVideoScoreEntity.getVideoId());
        //        BigDecimal scoreB = BigDecimal.valueOf(score);
        //        BigDecimal totalScore = BigDecimal.valueOf(videoEntity.getTotalScore());

        return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
    }

    /**
     * @param id    课程评分id
     * @param score
     * @return
     */
    @ApiOperation(value = "用户更新课程的评分", notes = "用户更新课程的评分")
    @GetMapping("updUserCourseScore/{id}/{score}")
    public JsonResult updUserCourseScore(@PathVariable String id, @PathVariable int score) {

        UserCourseScoreEntity userVideoScoreEntity =
                courseRepository.findById(UserCourseScoreEntity.class, id);
        if (userVideoScoreEntity != null) {
            CourseEntity videoEntity = courseRepository.findById(userVideoScoreEntity.getCourseId());
            videoEntity.setTotalScore(videoEntity.getTotalScore() - userVideoScoreEntity.getScore());
            userVideoScoreEntity.setScore(score);
            videoEntity.setTotalScore(videoEntity.getTotalScore() + userVideoScoreEntity.getScore());
            courseRepository.update(userVideoScoreEntity);
            courseRepository.update(videoEntity);
            return JsonResult.putSuccess();
        }
        return JsonResult.putFail("未查询到该用户课程评分，修改失败");
    }

    /**
     * @param id 课程评分id
     * @return
     */
    @ApiOperation(value = "用户删除课程评分", notes = "用户更新课程评分")
    @GetMapping("delUserCourseScore/{id}")
    public JsonResult delUserCourseScore(@PathVariable String id) {
        UserCourseScoreEntity userVideoScoreEntity =
                courseRepository.findById(UserCourseScoreEntity.class, id);
        if (userVideoScoreEntity != null) {
            CourseEntity videoEntity = courseRepository.findById(userVideoScoreEntity.getCourseId());
            videoEntity.setTotalScore(videoEntity.getTotalScore() - userVideoScoreEntity.getScore());
            videoEntity.setTotalPeopleScoreSize(videoEntity.getTotalPeopleScoreSize() - 1);

            courseRepository.remove(userVideoScoreEntity);
            courseRepository.update(videoEntity);
            return JsonResult.putSuccess();
        }
        return JsonResult.putFail("未查询到该用户课程评分，删除失败");
    }
}
